<?php
namespace app\admin\controller;
use think\Db;
/**
 * #提现管理#
 */
class Cash extends Common{
    /**
     * #提现展示#{展示用户提现列表}
     * @param  integer $module_id [description]
     * @param  string  $range     [description]
     * @return [type]             [description]
     */
    function index($module_id=1,$range='',$now_time=null){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        if(!is_null($now_time)){
            $range[0]=$now_time*1000;
            $range[1]=$now_time*1000;
        }
        $params=[
            'range'=>$range,
            'keyword'=>input('keyword/s',''),
            'type'=>input('type/s',''),
            'status'=>(string)input('status/d',0),
        ];
        $map=[];
        if(!empty($params['keyword'])){
            $map['tel|realname']=['tel|realname','like',"%{$params['keyword']}%"];
        }
        if($params['status']>0){
            $map['state']=(string)$params['status']-1;
        }
        if(!empty($params['type'])){
            $map['type']=$params['type'];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['s_time']=['s_time','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['s_time']=['s_time','>=',$range[0]/1000];
            }
        }
        $options=[
            'order'=>'s_time desc'
        ];
        $list=model($this->table)->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);
        $this->assign('params',json_encode($params));
        return view();
    }
    /**
     * #提现展示#{展示用户提现列表}
     * @param  integer $module_id [description]
     * @param  string  $range     [description]
     * @return [type]             [description]
     */
    function log($module_id=1,$range='',$now_time=null){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        if(!is_null($now_time)){
            $range[0]=$now_time*1000;
            $range[1]=$now_time*1000;
        }
        $params=[
            'range'=>$range,
            'keyword'=>input('keyword/s',''),
            'type'=>input('type/s',''),
            'status'=>(string)input('status/d',0),
        ];
        $map=['state'=>1];
        if(!empty($params['keyword'])){
            $map['tel|realname']=['tel|realname','like',"%{$params['keyword']}%"];
        }
        if($params['status']>0){
            $map['state']=(string)$params['status']-1;
        }
        if(!empty($params['type'])){
            $map['type']=$params['type'];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['e_time']=['e_time','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['e_time']=['e_time','>=',$range[0]/1000];
            }
        }
        $options=[
            'order'=>'e_time desc'
        ];
        $list=model($this->table)->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);
        $this->assign('params',json_encode($params));
        return view();
    }
    /**
     * #提现处理#{同意拒绝提现申请处理}
     * @param  integer $id     [description]
     * @param  string  $remark [description]
     * @param  integer $state  [description]
     * @return [type]          [description]
     */
    function handle($id=0,$remark='',$state=0){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该项数据不存在');
            }
            $has=model($this->table)->read(['id'=>$id],'id,uid,raw_money,money,bank_no,number,state,type');
            if(empty($has)){
                $this->error('该项数据可能已经删除');
            }
            if($has['state']>0){
                $this->error('该条提现记录已经处理过,请勿重复操作');
            }
            if(empty($remark)){
                $this->error('请填写备注项');
            }
            if($state>0){ //提现
                $result=true;
                Db::startTrans();
                try {
                    $e=model($this->table)->edit([
                        'id'=>$id,
                        'remark'=>$remark,
                        'e_time'=>time(),
                        'state'=>1,
                    ]);
                    if(!$e){
                        exception('审核失败，请稍后再试');
                    }
                    $user=model('member')->read(['id'=>$has['uid']],'tel');
                    $tel=preg_replace('/^(\d{3})\d+(\d{4})$/',"\$1****\$2", $user['tel']);
                    $res=model('news')->add([
                        'uid'=>$has['uid'],
                        'content'=>"恭喜{$tel}成功提现{$has['money']}元",
                        's_time'=>time(),
                    ]);
                    if(empty($res)){
                        exception('系统繁忙,记录写入失败');
                    }
                    $module=model('artmodule')->read(['name'=>'single'],'id');
                    $f=model('finance')->log($has['uid'],$has['uid'],$has['money'],3,[
                        'remark'=>'用户提现',
                        'module_id'=>$module['id'],
                    ]);
                    if(empty($f)){
                        exception('系统繁忙,记录写入失败');
                    }
                    if($has['type']==='alipay'){
                        $_data=[
                            'out_biz_no'=>$has['number'],
                            'payee_account'=>$has['bank_no'],
                            'amount'=>$has['money'],
                        ];
                        $res=alipayTransfer($_data);
                        model('aa_log')->add([
                            'msg'=>json_encode($res),
                            's_date'=>date('Y-m-d H:i')
                        ]);
                        $res=$res['alipay_fund_trans_toaccount_transfer_response'];
                        
                        if($res['code']==10000){
                            model('cash')->withdrawCash($has['id'],$has['uid'],$has['money'],'支付宝转账',$res['order_id']);
                        }elseif(isset($res['sub_msg'])){
                            exception($res['sub_msg']);
                        }else{
                            exception($res['msg']);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $result=$e->getMessage();
                }
                if(true!==$result){
                    logger('info',lang('withdrawals failed',[
                        $this->user['login_name'],
                        date('Y-m-d H:i:s'),
                        $has['number'],
                        $result,
                    ]));
                    $this->error($result);
                }else{
                    logger('info',lang('allow cash to withdraw',[
                        $this->user['login_name'],
                        date('Y-m-d H:i:s'),
                        $user['tel'],
                        $has['number'],
                        $has['raw_money'],
                        $has['money'],
                    ]));
                    $this->success('审核成功');
                    die;
                }
            }else{ //拒绝 退回提现金额
                $result=true;
                Db::startTrans();
                try {
                    
                    $inc=model('member')->where(['id'=>$has['uid']])->setInc('money',$has['raw_money']);
                    if(!$inc){
                        exception('系统繁忙，金额退回原账户失败!');
                    }
                    $e=model('cash')->edit([
                        'id'=>$id,
                        'remark'=>$remark,
                        'e_time'=>time(),
                        'state'=>2,
                    ]);
                    if(!$e){
                        exception('系统繁忙，处理失败!');
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $result=$e->getMessage();
                }
                if(true!==$result){
                    logger('info',lang('withdrawals failed',[
                        $this->user['login_name'],
                        date('Y-m-d H:i:s'),
                        $has['number'],
                        $result,
                    ]));
                    $this->error($result);
                }else{
                    $user=model('member')->read(['id'=>$has['uid']],'tel');
                    logger('info',lang('refusing cash to withdraw',[
                        $this->user['login_name'],
                        date('Y-m-d H:i:s'),
                        $user['tel'],
                        $remark,
                        $has['number'],
                        $has['raw_money'],
                        $has['money'],
                    ]));
                    $this->success('审核成功');
                    die;
                }
            }
        }
    }
}